package com.xbongbong.saas.model.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.domain.dao.MarketActivityDao;
import com.xbongbong.saas.domain.entity.ext.MarketActivityEntityExt;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.MarketActivitySubDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * @author feng.zheng
 * @version v1.0
 * @date 2019/1/22 16:44
 * @since v1.0
 */
@Service("marketActivityModel")
public class MarketActivityModelImpl implements MarketActivityModel {
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private MarketActivityDao marketActivityDao;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private MarketActivitySubDataModel marketActivitySubDataModel;

    @Override
    public Integer insert(MarketActivityEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setAddTime(now);
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);

        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = marketActivityDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
        paasEsModel.insert(insertDTO);

        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);
        return success;
    }

    @Override
    public Integer update(MarketActivityEntityExt entity) throws XbbException {
        long now = DateUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);
        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = marketActivityDao.update(entity);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = marketActivityDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);
        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    @Override
    public List<MarketActivityEntityExt> findEntitys(Map<String, Object> param) {
        List<MarketActivityEntityExt> entitys = marketActivityDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return marketActivityDao.getEntitysCount(param);
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return marketActivityDao.findEntitys(param);
    }

    @Override
    public MarketActivityEntityExt getByKey(Long key, String corpid) {
        MarketActivityEntityExt marketActivityEntityExt = marketActivityDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(marketActivityEntityExt), IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);
        return marketActivityEntityExt;
    }

    @Override
    public List<MarketActivityEntityExt> getByKeys(List<Long> keys, String corpid) {

        Map<String, Object> param = new HashMap<>();
        param.put("corpid", corpid);
        param.put("ids", keys);
        param.put("del", BasicConstant.ZERO);

        return findEntitys(param);
    }


    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            StandardizeDataUtil.standardizeList(updateDataList);
            integer = marketActivityDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
        }
        if (!subList.isEmpty()) {
            marketActivitySubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateDataList, String corpid,WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateDataList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateDataList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateDataList)) {
            StandardizeDataUtil.standardizeList(updateDataList);
            integer = marketActivityDao.updateBatch(updateDataList, corpid);
            paasEsModel.updateBatchMuchField(updateDataList, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            marketActivitySubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer restoreBatch(List<Long> dataIdList, String corpid, Integer del) throws XbbException{
        Integer count = marketActivityDao.restoreBatch(dataIdList, corpid, del);
        updateBatchDel(dataIdList, corpid, del);
        paasFormSubDataModel.restoreBatch(dataIdList, corpid, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);
        return count;
    }

//    @Override
//    public void insertBatch(List<PaasFormDataEntity> customerEntityExtList, boolean isImport) throws XbbException {
//        marketActivityDao.insertBatch(customerEntityExtList);
//        //ES数据插入
//        List<InsertDTO> insertList = new ArrayList<>();
//        for (PaasFormDataEntity item : customerEntityExtList) {
//            InsertDTO insertDTO = new InsertDTO();
//            insertDTO.setEsId(item.getCorpid() + "_" + item.getId());
//            item.setDataId(item.getId());
//            insertDTO.setSource(BeanUtil.convertBean2Map(item));
//            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
//            insertList.add(insertDTO);
//        }
//        if (isImport) {
//            paasEsModel.insertBatch(insertList, WriteRequest.RefreshPolicy.NONE);
//        } else {
//            paasEsModel.insertBatch(insertList);
//        }
//
//    }
    @Override
    public Integer deleteBatch(List<Long> idIn, String corpid) throws XbbException {
        Integer integer = marketActivityDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
        paasEsModel.delete(deleteDTO);
        paasFormSubDataModel.deleteByDataId(key,corpid,IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY_SUB);
        return marketActivityDao.deleteByKey(key,corpid);
    }

    private void updateBatchDel(List<Long> dataIdList, String corpid, Integer del) throws XbbException{
        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("del", del);
        map.put("updateTime",DateTimeUtil.getInt());
        paasFormDataEsModel.updateBatch(dataIdList, corpid, map,IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
    }


    @Override
    public Integer updateTime(Long id,String corpid) throws XbbException {
        long now = DateUtil.getInt();
        // 更新时间
        Integer success = marketActivityDao.updateTime(now, id, corpid);
        // 更新es
        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        paasFormDataEntity.setId(id);
        paasFormDataEntity.setDataId(id);
        paasFormDataEntity.setCorpid(corpid);
        paasFormDataEntity.setUpdateTime(now);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_MARKET_ACTIVITY);
        paasEsModel.update(insertDTO);
        return success;
    }

    @Override
    public List<String> listAllCorpid() throws XbbException {
        return marketActivityDao.listAllCorpid();
    }

}
